package com.sangmo.fts.user.repo;

import com.sangmo.boot.framework.plugin.dataview.spi.jpa.IJpaDataViewRepo;
import com.sangmo.fts.user.model.Permission;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Set;

@Repository
public interface PermissionRepo extends IJpaDataViewRepo<Permission> {

    @Query("SELECT a.uri FROM Permission a WHERE " +
            "EXISTS(SELECT 1 FROM RolePermission b WHERE b.permissionId = a.id AND " +
            "EXISTS (SELECT 1 FROM User c WHERE c.id = :userId AND c.roleId = b.roleId))")
    Collection<String> findPermissionsByUserId(@Param("userId")Long userId);

    @Query("SELECT a.uri FROM Permission a WHERE " +
            "EXISTS(SELECT 1 FROM RolePermission b WHERE b.permissionId = a.id AND " +
            "EXISTS (SELECT 1 FROM Role c WHERE c.code IN (:roles) AND c.id = b.roleId)) AND " +
            "a.application = :application")
    Collection<String> findByApplicationAndRoleIn(@Param("application") String application, @Param("roles") Set<String> roles);

    Collection<Permission> findByApplication(String application);
}
